import React from 'react';
import { DragSource } from 'react-dnd';
import { getEmptyImage } from 'react-dnd-html5-backend';
import { Button, Dropdown, Icon, Menu, Popover } from 'antd';
import { summaryWayMap, sequenceWayMap } from 'containers/data-center/report-management/custom-report/custom-report.modal';
import InputLanguage from 'components/template/input-language';
import { messages } from 'share/common';

/**
 * 从然哥18年写的 react-dnd copy过来的
 *
 * 页面左侧图标可拖拽组件块
 */
class DroppedDataDragItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      popoverVisible: false,
      currentI18n: {
        name: this.props.widget.fieldDisplayName || this.props.widget.columnDisplayName,
        i18n: this.props.widget.i18n ? (this.props.widget.i18n.fieldDisplayName || this.props.widget.i18n.columnDisplayName) : []
      }
    };
    this.shouldNotClose = false;
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.setState({
      currentI18n: {
        name: nextProps.widget.fieldDisplayName || nextProps.widget.columnDisplayName,
        i18n: nextProps.widget.i18n ? (nextProps.widget.i18n.fieldDisplayName || nextProps.widget.i18n.columnDisplayName) : []
      }
    })
  }

  componentDidMount() {
    //链接拖拽的预览图片，用官方api给定一个空图片
    this.props.connectDragPreview(getEmptyImage(), {
      captureDraggingState: true,
    });
  }

  onMenuSelect = (e) => {
    const { widget } = this.props;
    let map = ['asc', 'desc', 'default_order'];
    if (map.indexOf(e.key) !== -1) {
      this.props.onChangeDataStatus && this.props.onChangeDataStatus(e.key, widget, true);
      this.setState({ visible: false });
    } else {
      this.props.onChangeDataStatus && this.props.onChangeDataStatus(e.key, widget, false);
      this.setState({ visible: false });
    }
  };

  onHide = () => {
    this.setState({ popoverVisible: false });
  };

  handleVisibleChange = (popoverVisible) => {
    if (!this.shouldNotClose) {
      this.setState({ popoverVisible });
    }
  };

  i18nChange = (value) => {
    this.setState({ currentI18n: value });
  };

  saveI18n = () => {
    const { widget } = this.props;
    const { currentI18n } = this.state;
    this.props.onSaveI18n && this.props.onSaveI18n(currentI18n, widget);
    this.setState({ popoverVisible: false });
  };

  onVisibleChange = (e) => {
    if (!this.shouldNotClose) {
      if (!e) {
        this.setState({ visible: e, popoverVisible: e });
      } else {
        this.setState({ visible: e });
      }
    }
  };

  render() {
    const { widget, type, connectDragSource, isDragging } = this.props;
    const { currentI18n, visible } = this.state;
    const numberType = ['bigdecimal', 'number'].indexOf(widget.dataType) !== -1;

    const content = (
      <div>
        <InputLanguage clickedHideI18n={() => {
          this.shouldNotClose = false;
        }} clickedI18n={() => {
          this.shouldNotClose = true;
        }} value={currentI18n} onChange={this.i18nChange}/>
        <div style={{ marginTop: 12, textAlign: 'right' }}>
          <Button onClick={this.onHide}>{messages('common.cancel')/*取消*/}</Button>
          <Button onClick={this.saveI18n} style={{ marginLeft: 8 }}
                  type='primary'>{messages('common.ok')/*确定*/}</Button>
        </div>
      </div>
    );
    const indicatorMenu = (
      <Menu className={'custom-report-menu-class'} onClick={this.onMenuSelect}>
        <Menu.Item key="name">
          <Popover
            placement="rightTop"
            visible={this.state.popoverVisible}
            content={content}
            onVisibleChange={this.handleVisibleChange}
            trigger={['click']}
          >
            <div onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
            }}>{messages('basic-10.key94')/*修改显示名称*/}</div>
          </Popover>
        </Menu.Item>
        {['indicator'].indexOf(type) !== -1 && <Menu.SubMenu className={'custom-report-sub-menu-id'} key='calculate'
                       title={messages('basic-10.key95')/*汇总计算方式*/}>
          <Menu.Item disabled={!numberType} key="sum">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key81')/*求和*/}
              </div>
              {widget.summaryWay === 'sum' && <Icon type="check"/>}
            </div>
          </Menu.Item>
          <Menu.Item disabled={!numberType} key="avg">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key82')/*平均*/}
              </div>
              {widget.summaryWay === 'avg' && <Icon type="check"/>}
            </div>
          </Menu.Item>
          <Menu.Item disabled={!numberType} key="max">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key83')/*最大值*/}
              </div>
              {widget.summaryWay === 'max' && <Icon type="check"/>}
            </div>
          </Menu.Item>
          <Menu.Item disabled={!numberType} key="min">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key84')/*最小值*/}
              </div>
              {widget.summaryWay === 'min' && <Icon type="check"/>}
            </div>
          </Menu.Item>
          <Menu.Item key="count">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key85')/*计数*/}
              </div>
              {widget.summaryWay === 'count' && <Icon type="check"/>}
            </div>
          </Menu.Item>
        </Menu.SubMenu>}
        {['indicator', 'show'].indexOf(type) !== -1 && <Menu.SubMenu className={'custom-report-sub-menu-id'} key='sort'
                       title={messages('basic-10.key96')/*排序*/}>
          <Menu.Item key="default_order">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key86')/*默认*/}
              </div>
              {widget.sequenceWay === 'default_order' && <Icon type="check"/>}
            </div>
          </Menu.Item>
          <Menu.Item key="asc">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key88')/*升序*/}
              </div>
              {widget.sequenceWay === 'asc' && <Icon type="check"/>}
            </div>
          </Menu.Item>
          <Menu.Item key="desc">
            <div className='flex-box'>
              <div>
                {messages('basic-10.key87')/*降序*/}
              </div>
              {widget.sequenceWay === 'desc' && <Icon type="check"/>}
            </div>
          </Menu.Item>
        </Menu.SubMenu>}
        <Menu.Item key="delete">
          <div onClick={(e) => {
            e.stopPropagation();
            this.setState({ visible: false }, () => {
              this.props.deleteItem && this.props.deleteItem(widget);
            });
          }}>
            {messages('basic-10.key97')/*删除值*/}
          </div>
        </Menu.Item>
      </Menu>
    );

    return connectDragSource(
      <div
        draggable={true}
        onMouseOver={()=>{this.props.onItemMouseOver && this.props.onItemMouseOver(widget)}}
        onMouseLeave={()=>{this.props.onItemMouseLeave && this.props.onItemMouseLeave()}}
        onClick={(e)=>{e.stopPropagation();this.props.onItemClick && this.props.onItemClick(widget)}}
      >
        <Dropdown visible={visible} onVisibleChange={this.onVisibleChange}
                  overlay={indicatorMenu}
                  trigger={['click']}>
          <span>
            <Icon type="down"/>
            {widget.columnDisplayName || widget.fieldDisplayName || '-'}
            {type === 'indicator' ? `(${summaryWayMap[widget.summaryWay]}${widget.sequenceWay !== 'default_order' ? `, ${sequenceWayMap[widget.sequenceWay]}` : ''})` : (
              (type === 'show' && widget.sequenceWay !== 'default_order') ? `(${sequenceWayMap[widget.sequenceWay]})` : ''
            )}
            <Icon type="close" onClick={(e) => {
              e.stopPropagation();
              this.props.deleteItem && this.props.deleteItem(widget);
            }}/>
          </span>
        </Dropdown>
      </div>
    );
  }
}

DroppedDataDragItem.propTypes = {
  widget: React.PropTypes.object,
  connectDragSource: React.PropTypes.func.isRequired,  //自动注入
  connectDragPreview: React.PropTypes.func.isRequired,  //自动注入
  isDragging: React.PropTypes.bool.isRequired
};

export default DragSource(
  'data-item',
  {
    beginDrag(props) {
      props.onDragDroppedItem && props.onDragDroppedItem(props.widget);
      return props.widget;
    },
    endDrag(props) {
      props.onDragEnd && props.onDragEnd();
      return props.widget;
    }
  },
  (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    connectDragPreview: connect.dragPreview(),
    isDragging: monitor.isDragging(),
  }))(DroppedDataDragItem)
